package aos.server.skype;

import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import aos.server.ServerProperties;
import aos.server.robot.RobotControllerProxy;

import com.skype.Application;
import com.skype.ApplicationAdapter;
import com.skype.Call;
import com.skype.CallListener;
import com.skype.Skype;
import com.skype.SkypeException;
import com.skype.Stream;
import com.skype.StreamAdapter;
import com.skype.User;

/**
 * 
 * This class create a Skype application and dispatch requests from the client.
 * 
 * @author Yannic
 *
 */
public class SkypeServer {

	Logger logger = Logger.getLogger(SkypeServer.class);
	static RobotControllerProxy controller;

	public SkypeServer(RobotControllerProxy controller) {
		SkypeServer.controller = controller;

		try {
			Application application = Skype.addApplication(
					ServerProperties.getInstance().getProperty(ServerProperties.APPLICATION_NAME));
			application.addApplicationListener(new ApplicationAdapter() {
				@Override
				public void connected(Stream stream) throws SkypeException {
					logger.info("Connected to client:" + stream.getId());
					stream.addStreamListener(new StreamAdapter() {
						@Override
						public void textReceived(String receivedText) throws SkypeException {
							logger.info("Received message from client:" + receivedText);

							StringTokenizer tokenizer = new StringTokenizer(receivedText, ",");
							try {
								if (tokenizer.countTokens() == 2) {
									float x = Float.valueOf(tokenizer.nextToken());
									float y = Float.valueOf(tokenizer.nextToken());
									SkypeServer.controller.setPosition(x, y);                    		
								} else {
									logger.warn("Message from client has not the expected format. Message discarded");
								}
							}
							catch(NumberFormatException e) {
								logger.warn("Message from client has not the expected format. Message discarded");
							}
						}
					});
				}
			});

			Skype.addCallListener( new CallListener() {

				public void callMaked(Call makedCall) throws SkypeException {
					// TODO Auto-generated method stub

				}

				public void callReceived(Call receivedCall) throws SkypeException {
					User user = receivedCall.getPartner();
					if (ServerProperties.getInstance().isAcceptedUser(user.getId())) {
						logger.info("Answered call id: " + receivedCall.getId());
						receivedCall.answer();
						try {
							Thread.sleep(1000);
						} catch(InterruptedException e) {
							logger.warn("Waiting time interrupted", e);
						}
						receivedCall.setReceiveVideoEnabled(true); // issue with framework send/receive are wrong
					}
				}
			});
		} catch (SkypeException e) {
			logger.fatal("System exit with error", e);
			System.exit(-1);
		}
	}

}